//
//  AMPSADJGNativeExpressAdapter.m
//  AdScopeDemo
//
//  Created by apple on 2025/5/22.
//

#import "AMPSADJGNativeExpressAdapter.h"
#import <ADJgSDK/ADJgSDKNativeAd.h>
#import "AMPSADJGNativeExpressView.h"
#import <AdScopeFoundation/AdScopeFoundation.h>
#import "AMPSADJGSDKManagerAdapter.h"

@interface AMPSADJGNativeExpressAdapter () <ADJgSDKNativeAdDelegate>

@property (nonatomic, strong) ADJgSDKNativeAd *nativeExpressAd;

@property (nonatomic, assign) BOOL isBiddingRequest;

@property (nonatomic, strong) NSMapTable <UIView<ADJgAdapterNativeAdViewDelegate> *, AMPSADJGNativeExpressView *> *nativeMapTable;

@property (nonatomic, strong) AdScopeTimer *timeoutTimer;

@property (nonatomic, strong) AMPSAdConfiguration *adConfiguration;

@end

@implementation AMPSADJGNativeExpressAdapter

- (void)requestBiddingPriceWithSpaceId:(NSString *)spaceId
                       adConfiguration:(AMPSAdConfiguration *)adConfiguration {
    self.isBiddingRequest = YES;
    [self loadAdWithSpaceId:spaceId adConfiguration:adConfiguration];
}

- (void)loadAdWithSpaceId:(nonnull NSString *)spaceId adConfiguration:(nonnull AMPSAdConfiguration *)adConfiguration {
    if (AMPSADJGSDKManagerAdapter.initState != kAdScopeMediationAdapterInitSDKStateSuccess) {
        __weak typeof(self)weakSelf = self;
        [AMPSADJGSDKManagerAdapter startAsyncWithAppId:self.appId configuration:self.sdkConfiguration results:^(BOOL adapterResult) {
            __strong typeof(weakSelf)strongSelf = weakSelf;
            if (adapterResult) {
                dispatch_async(dispatch_get_main_queue(), ^{
                    [self gdtLoadAdWithSpaceId:spaceId adConfiguration:adConfiguration];
                });
            } else {
                if (strongSelf.isBiddingRequest) {
                    NSError *error = [NSError errorWithDomain:@"xyz.adscope.MediationErrorDomain" code:250401 userInfo:@{@"NSLocalizedDescription": @"AMPSADJGSDKManagerAdapter init fail"}];
                    if (strongSelf.bidDelegate && [strongSelf.bidDelegate respondsToSelector:@selector(requestBiddingPriceFail:error:ext:)]) {
                        [strongSelf.bidDelegate requestBiddingPriceFail:strongSelf error:error ext:adConfiguration.ext];
                    }
                } else {
                    NSError *error = [NSError errorWithDomain:@"xyz.adscope.MediationErrorDomain" code:270401 userInfo:@{@"NSLocalizedDescription": @"AMPSADJGSDKManagerAdapter init fail"}];
                    if (strongSelf.customDelegate && [strongSelf.customDelegate respondsToSelector:@selector(nativeAdManagerLoadFail:error:ext:)]) {
                        [strongSelf.customDelegate nativeAdManagerLoadFail:strongSelf error:error ext:adConfiguration.ext];
                    }
                }
            }
        }];
    } else {
        [self gdtLoadAdWithSpaceId:spaceId adConfiguration:adConfiguration];
    }
}

- (void)gdtLoadAdWithSpaceId:(NSString *)spaceId adConfiguration:(AMPSAdConfiguration *)adConfiguration {
    self.nativeExpressAd = [[ADJgSDKNativeAd alloc] initWithAdSize:adConfiguration.adSize];
    self.nativeExpressAd.posId = spaceId;
    self.nativeExpressAd.delegate = self;
    self.nativeExpressAd.controller = adConfiguration.viewController;
    self.adConfiguration = adConfiguration;
    if (adConfiguration.videoSound == 1) {
        self.nativeExpressAd.muted = NO;
    }
    CGFloat floatValue = adConfiguration.timeoutInterval/1000 > 0 ? adConfiguration.timeoutInterval/1000 : 5;
    self.timeoutTimer = [AdScopeTimer adScopeScheduledWeakTimerWithTimeInterval:floatValue target:self selector:@selector(timeoutTimerSelector) repeats:NO];
//    [self.nativeExpressAd load:(int)adConfiguration.adCount];//加载3条，第1条关闭时会直接走[AMPSADJGNativeExpressAdapter removeAd]
    [self.nativeExpressAd load:1];
}

- (void)timeoutTimerSelector {
//    NSError *error = [NSError errorWithDomain:@"xyz.adscope.MediationErrorDomain" code:-9999 userInfo:@{@"NSLocalizedDescription": @"AMPSADJGNativeExpressAdapter load ad timeout"}];
    [self adjg_nativeAdFailToLoad:self.nativeExpressAd errorModel:[ADJgAdapterErrorDefine new]];
}

- (void)removeAd {
    if (_timeoutTimer) {
        [_timeoutTimer invalidate];
        _timeoutTimer = nil;
    }
    if (_viewsArray) {
        _viewsArray = nil;
    }
    if (_nativeExpressAd) {
        if ([_nativeExpressAd respondsToSelector:@selector(delegate)]) {
            _nativeExpressAd.delegate = nil;
        }
        _nativeExpressAd = nil;
    }
}

- (BOOL)isValid {
    return YES;
}

- (void)loadC2SAdWithSpaceId:(NSString *)spaceId
                biddingToken:(id)biddingToken
             adConfiguration:(AMPSAdConfiguration *)adConfiguration {
    if (self.isLoadAdSuccess) {
        if (self.customDelegate && [self.customDelegate respondsToSelector:@selector(nativeAdManagerLoadSuccess:ext:)]) {
            [self.customDelegate nativeAdManagerLoadSuccess:self ext:self.adConfiguration.ext];
        }
    }
}

- (void)loadS2SAdWithSpaceId:(NSString *)spaceId
                biddingToken:(id)biddingToken
             adConfiguration:(AMPSAdConfiguration *)adConfiguration {
    
}

/**
 * 拉取原生模板广告成功
 */
- (void)adjg_nativeAdSucessToLoad:(ADJgSDKNativeAd *)nativeAd
                      adViewArray:(NSArray<__kindof UIView<ADJgAdapterNativeAdViewDelegate> *> *)adViewArray {
    if (_timeoutTimer) {
        [_timeoutTimer invalidate];
        _timeoutTimer = nil;
    }
    NSMutableArray *nativeAdViewArr = [NSMutableArray array];
    NSInteger ecpm = 0;
    for (UIView<ADJgAdapterNativeAdViewDelegate> *nativeExpressview in adViewArray) {
        ADJgSDKExtInfo *extInfo = [nativeExpressview adjg_extInfo];
        ecpm = [extInfo.ecpm integerValue];
        AMPSADJGNativeExpressView *adjgNativeExpressView = [[AMPSADJGNativeExpressView alloc] init];
        adjgNativeExpressView.adjgNativeAdView = nativeExpressview;
        if (adjgNativeExpressView && nativeExpressview) {
            [self.nativeMapTable setObject:adjgNativeExpressView forKey:nativeExpressview];
            [nativeAdViewArr addObject:adjgNativeExpressView];
        }
    }
    self.viewsArray = [NSArray arrayWithArray:nativeAdViewArr];
    self.isLoadAdSuccess = YES;
    if (!self.isBiddingRequest) {
        if (self.customDelegate && [self.customDelegate respondsToSelector:@selector(nativeAdManagerLoadSuccess:ext:)]) {
            [self.customDelegate nativeAdManagerLoadSuccess:self ext:self.adConfiguration.ext];
        }
        return;
    }
    if (ecpm > 0) {
        if (self.bidDelegate && [self.bidDelegate respondsToSelector:@selector(requestBiddingPriceSuccess:ext:)]) {
            [self.bidDelegate requestBiddingPriceSuccess:self ext:self.adConfiguration.ext];
        }
    } else {
        if (self.bidDelegate && [self.bidDelegate respondsToSelector:@selector(requestBiddingPriceFail:error:ext:)]) {
            NSError *error = [NSError errorWithDomain:@"xyz.adscope.MediationErrorDomain" code:250401 userInfo:@{@"NSLocalizedDescription": @"AMPSADJGNativeExpressAdapter ad bidding fail,ecpm less than 0"}];
            [self.bidDelegate requestBiddingPriceFail:self error:error ext:self.adConfiguration.ext];
        }
    }
    
}

/**
 * 拉取原生模板广告失败
 */
- (void)adjg_nativeAdFailToLoad:(ADJgSDKNativeAd *)nativeAd
                     errorModel:(ADJgAdapterErrorDefine *)errorModel {
    NSError *tempError = ADJgAdapterError(ADJgAdapterErrorDomain, errorModel.code, errorModel.message);
    if (self.isBiddingRequest) {
        if (self.bidDelegate && [self.bidDelegate respondsToSelector:@selector(requestBiddingPriceFail:error:ext:)]) {
            [self.bidDelegate requestBiddingPriceFail:self error:tempError ext:self.adConfiguration.ext];
        }
    } else {
        if (self.customDelegate && [self.customDelegate respondsToSelector:@selector(nativeAdManagerLoadFail:error:ext:)]) {
            [self.customDelegate nativeAdManagerLoadFail:self error:tempError ext:self.adConfiguration.ext];
        }
    }
    [self removeAd];
}

/**
 * 原生模板广告渲染成功, 此时的 nativeExpressAdView.size.height 根据 size.width 完成了动态更新。
 */
- (void)adjg_nativeAdViewRenderOrRegistSuccess:(UIView<ADJgAdapterNativeAdViewDelegate> *)adView {
    AMPSADJGNativeExpressView *adjgNativeExpressView = [self.nativeMapTable objectForKey:adView];
    adjgNativeExpressView.frame = adView.frame;
    [adjgNativeExpressView addSubview:adView];
//    if ([nativeExpressAdView respondsToSelector:@selector(controller)]) {
//        nativeExpressAdView.controller = adjgNativeExpressView.viewController;
//    }
    if (adjgNativeExpressView.viewDelegate && [adjgNativeExpressView.viewDelegate respondsToSelector:@selector(nativeViewRenderSuccess:ext:)]) {
        [adjgNativeExpressView.viewDelegate nativeViewRenderSuccess:adjgNativeExpressView ext:self.adConfiguration.ext];
    }
}

///**
// * 原生模板广告渲染失败
// */
- (void)adjg_nativeAdViewRenderOrRegistFail:(UIView<ADJgAdapterNativeAdViewDelegate> *)adView {
    AMPSADJGNativeExpressView *adjgNativeExpressView = [self.nativeMapTable objectForKey:adView];
    if (adjgNativeExpressView.viewDelegate && [adjgNativeExpressView.viewDelegate respondsToSelector:@selector(nativeViewRenderFail:error:ext:)]) {
        [adjgNativeExpressView.viewDelegate nativeViewRenderFail:adjgNativeExpressView error:nil ext:self.adConfiguration.ext];
    }
    [adjgNativeExpressView removeAd];
}

///**
// * 原生模板广告曝光回调
// */
- (void)adjg_nativeAdExposure:(ADJgSDKNativeAd *)nativeAd
                       adView:(__kindof UIView<ADJgAdapterNativeAdViewDelegate> *)adView {
    AMPSADJGNativeExpressView *adjgNativeExpressView = [self.nativeMapTable objectForKey:adView];
    if (adjgNativeExpressView.viewDelegate && [adjgNativeExpressView.viewDelegate respondsToSelector:@selector(nativeViewExposured:)]) {
        [adjgNativeExpressView.viewDelegate nativeViewExposured:adjgNativeExpressView];
    }
}

///**
// * 原生模板广告点击回调
// */
- (void)adjg_nativeAdClicked:(ADJgSDKNativeAd *)nativeAd
                      adView:(__kindof UIView<ADJgAdapterNativeAdViewDelegate> *)adView {
    AMPSADJGNativeExpressView *adjgNativeExpressView = [self.nativeMapTable objectForKey:adView];
    if (adjgNativeExpressView.viewDelegate && [adjgNativeExpressView.viewDelegate respondsToSelector:@selector(nativeViewDidClick:)]) {
        [adjgNativeExpressView.viewDelegate nativeViewDidClick:adjgNativeExpressView];
    }
}

///**
// * 原生模板广告被关闭
// */
- (void)adjg_nativeAdClose:(ADJgSDKNativeAd *)nativeAd
                    adView:(__kindof UIView<ADJgAdapterNativeAdViewDelegate> *)adView {
    AMPSADJGNativeExpressView *adjgNativeExpressView = [self.nativeMapTable objectForKey:adView];
    if (adjgNativeExpressView.viewDelegate && [adjgNativeExpressView.viewDelegate respondsToSelector:@selector(nativeViewDidClose:)]) {
        [adjgNativeExpressView.viewDelegate nativeViewDidClose:adjgNativeExpressView];
    }
    [adjgNativeExpressView removeAd];
}

- (NSMapTable *)nativeMapTable {
    if (!_nativeMapTable) {
        _nativeMapTable = [NSMapTable weakToWeakObjectsMapTable];
    }
    return _nativeMapTable;
}

- (void)dealloc {
    [self removeAd];
}

@end
